

import os
import cv2
import shutil
import csv
import time
import numpy as np
from typing import Dict, Any, List, Optional
from .classifier3class import ClassificationService
from .segmentation_analyzer import SegmentationAnalyzerService
from devdeploy.src import get_optimal_device, prepare_output_directory

class DeterminationOfBandedStructureOfSteel_Service:
    """
    带状组织判级服务
    
    。
    """
    
    def __init__(self, classmodel_path: str,segmodel_path: str, classdevice: Optional[str] = None, segdevice: Optional[str] = None):
        """
        初始化分类 分割分析服务
        
        Args:
            model_path (str): 模型文件路径
            device (str, optional): 推理设备，如果为None则自动选择
        """
        self.classmodel_path = classmodel_path
        self.classdevice = classdevice or get_optimal_device()
        
        # 初始化分类分析器
        try:
            self.class_analyzer = ClassificationService(
                model_path=self.classmodel_path,
                device=self.classdevice
            )
            print(f"分割分析服务初始化成功，使用设备: {self.classdevice}")
        except Exception as e:
                raise RuntimeError(f"初始化分割分析服务失败: {str(e)}")
        
        self.segmodel_path = segmodel_path
        self.segdevice = segdevice or get_optimal_device()
        
        # 初始化分割分析器
        try:
            self.seg_analyzer = SegmentationAnalyzerService(
                model_path=self.segmodel_path,
                device=self.segdevice
            )
            print(f"分割分析服务初始化成功，使用设备: {self.segdevice}")
        except Exception as e:
                raise RuntimeError(f"初始化分割分析服务失败: {str(e)}")
    
    def analyze_oneimg(self,image_dir,filename,output_folder,results_folder):
        try:
            classresults = self.class_analyzer.analyze_oneimg(image_dir+filename,output_folder)   
            Segresults,Segresultimg ,resultpaint= self.seg_analyzer.analyze_oneimg(image_dir+filename,output_folder)   
            cv2.imencode(".jpg", Segresultimg)[1].tofile(output_folder+filename) 
            cv2.imencode(".jpg", resultpaint)[1].tofile(results_folder+filename) 
            classf=classresults['result']
            segclassf=Segresults['result']
            resultout = filename+','+str(classf)+','+str(segclassf)+','+str((segclassf))
            # print(resultout)
            return resultout,classf,segclassf
               
                
            # cv2.imencode(".jpg", heatmap)[1].tofile(middle_image_dir+filename) 
                
            #绘制数量
                   
            # jx_f_seg.put_text_with_background(imagere,str(f"class:{max(classf,segclassf)}"),(80,80),cv2.FONT_HERSHEY_SIMPLEX,3,(255,255,0),(50,30, 30),3)   
            
                

        except Exception as e:
                raise RuntimeError(f"分析单张图像 分类 和 分割 过程错误: {str(e)}")
                return None


    def analyze_folder(self,imgsDir_path,outResultsDir_path):
         
        result = {
            'success': False,
            'reuslts': [],
            'message': '',
            'total_images': 0,
            'processed_images': 0,
            'failed_images': 0
        }
        try:
            # image_dir = imgsDir_path +'test_data/test_images/'
            image_dir = os.path.join(imgsDir_path, 'test_data/test_images/')
            image_dir_ori = imgsDir_path + '/'
        
            if not os.path.exists(image_dir):
                os.makedirs(image_dir)
            lsTemp = os.listdir(image_dir)
            for iTemp in lsTemp:
                pathTemp = os.path.join(image_dir, iTemp)
                os.remove(pathTemp)
                print(pathTemp)
                
            # fileout=  imgsDir_path +'test_data/fileoutput'  

            fileout = os.path.join(imgsDir_path, 'test_data/fileoutput/')
            if not os.path.exists(fileout):
                os.makedirs(fileout)
            lsTemp = os.listdir(fileout)
            for iTemp in lsTemp:
                pathTemp = os.path.join(fileout, iTemp)
                os.remove(pathTemp)
                print(pathTemp)
            # middle_image_dir = imgsDir_path +'test_data/middle_results/'   

            middle_image_dir = os.path.join(imgsDir_path, 'test_data/middle_results/') 
            if not os.path.exists(middle_image_dir):
                os.makedirs(middle_image_dir)
            lsTemp = os.listdir(middle_image_dir)
            for iTemp in lsTemp:
                pathTemp = os.path.join(middle_image_dir, iTemp)
                os.remove(pathTemp)
                print(pathTemp)
                
            # segpath=imgsDir_path +'test_data/seg_results'
            segpath = os.path.join(imgsDir_path, 'test_data/seg_results/') 
            if not os.path.exists(segpath):
                os.makedirs(segpath)
            lsTemp = os.listdir(segpath)
            for iTemp in lsTemp:
                pathTemp = os.path.join(segpath, iTemp)
                os.remove(pathTemp)
                
            # Fsegpath=imgsDir_path +'test_data/F_results'  
            Fsegpath = os.path.join(imgsDir_path, 'test_data/F_results/') 
            if not os.path.exists(Fsegpath):
                os.makedirs(Fsegpath)
            lsTemp = os.listdir(Fsegpath)
            for iTemp in lsTemp:
                pathTemp = os.path.join(Fsegpath, iTemp)
                os.remove(pathTemp)
            print("清理文件夹完成")
            
            resultEnd = []
            for filename in os.listdir(image_dir_ori):
                tmp = filename.split('.')[-1]
                classf=-1
                segclassf=-1
                if tmp == 'jpg' or tmp == 'bmp' or tmp == 'png':
                    # img = cv2.imread(image_dir_ori+filename)
                    img=cv2.imdecode(np.fromfile(image_dir_ori+filename,dtype=np.uint8),cv2.IMREAD_COLOR)
                    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
                
                    fm = cv2.Laplacian(gray,cv2.CV_64F).var()
                    if fm >= 10:
                        print((image_dir_ori+filename) + ' -> ' + (image_dir+filename))
                        shutil.copyfile(image_dir_ori+filename,image_dir+filename)
                        
                        # heatmap,result,classf = jx_classifer.classinfer(image_dir+filename)
                        # segclassf,imagere=jx_f_seg.Seginfer(image_dir+filename,Fsegpath,segpath)
                        
                        # output_folder = segpath
                        resultout,classr,segr = self.analyze_oneimg(image_dir,filename,segpath,Fsegpath)
                        print(resultout)
                        resultEnd.append({
                            'file_name': filename,
                            'class_ratios': segr,
                            'class_message': resultout
                            # 'image_shape': gray.shape()
                        })
                        
                        # cv2.imencode(".jpg", heatmap)[1].tofile(middle_image_dir+filename) 
                        
                        #     #绘制数量
                        # # cv2.putText(imagere,str(f"class:{max(classf,segclassf)}"),(80,80),cv2.FONT_HERSHEY_SIMPLEX,3,(255,0,0),3)   
                        # jx_f_seg.put_text_with_background(imagere,str(f"class:{max(classf,segclassf)}"),(80,80),cv2.FONT_HERSHEY_SIMPLEX,3,(255,255,0),(50,30, 30),3)   
                        # # if count==0:    
                        # #             #如果cots 为空，则说明没有检测到物体，则绘制提示信息
                        # #     cv2.putText(image,"no object detected",(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),2)
                        # output_path = os.path.join(Fsegpath, filename)
                        # cv2.imencode(".jpg", imagere)[1].tofile(output_path)   
                        result['processed_images'] += 1 
                    else:
                        print((image_dir_ori+filename) + ' --x-> ' + (image_dir+filename))
                        result['failed_images'] += 1
                        # resultEnd.append((image_dir_ori+filename) + ' --x-> ' + (image_dir+filename) )
                else:
                    print((image_dir_ori+filename)+"pass")
                    result['failed_images'] += 1
                    # resultEnd.append((image_dir_ori+filename)+"pass" )
            print(resultEnd)        
            # result = FF_inferencer(imgpath)[0]
            # fileoutput = path_set.workspace_dir +'test_data/fileoutput/end.txt'
            fileoutput = os.path.join(imgsDir_path, 'test_data/fileoutput/end.txt') 
            outputimageStr = "end"
            with open(fileoutput,mode='w',encoding = 'utf-8') as file_obj:
                file_obj.write(outputimageStr)
            result['success'] = True
            result['results'] = resultEnd
            result['message'] = f"分析完成！成功处理 {result['processed_images']} 个文件，失败 {result['failed_images']} 个文件"
        #  return resultEnd
        except Exception as e:
            result['message'] = f"分析文件夹时发生错误: {str(e)}"
        
        return result
    

if __name__ == '__main__':
    # imgspath = path_set.workspace_dir +'inputdata'
    imgspath = r"devdeploy\data\ff"
    class_model_path = r"../weights/JinXiang_FF/class/fullmodel_best.onnx"
    seg_model_path = r"../weights/JinXiang_FF/seg/fullmodel_best.onnx"
    classdevice='cuda'
    segdevice='cuda'
    dobsinfer=DeterminationOfBandedStructureOfSteel_Service(class_model_path,seg_model_path,classdevice,segdevice)
    result = dobsinfer.analyze_folder(imgspath,imgspath)
    print(result)
 